package com.yunshipei.core.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.ValueCallback;

import com.yunshipei.core.ui.client.EnterWebChromeClient;
import com.yunshipei.core.ui.client.EnterWebViewClient;

import org.xwalk.core.XWalkDownloadListener;
import org.xwalk.core.XWalkNavigationHistory;
import org.xwalk.core.XWalkView;

public class EnterWebView extends XWalkView {

    private EnterWebChromeClient webChromeClient;

    public EnterWebView(Context context) {
        super(context);
    }

    public EnterWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public boolean forwardHistory() {
        if (super.getNavigationHistory().canGoForward()) {
            super.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.FORWARD, 1);
            return true;
        }
        return false;
    }

    public boolean backHistory() {
        if (super.getNavigationHistory().canGoBack()) {
            super.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
            return true;
        }
        return false;
    }

    public void setWebViewClient(EnterWebViewClient client) {
        setResourceClient(client);
    }

    public void setYspDownloadListener(XWalkDownloadListener xWalkDownloadListener) {
        setDownloadListener(xWalkDownloadListener);
    }

    public void setWebChromeClient(EnterWebChromeClient chromeClient) {
        this.webChromeClient = chromeClient;
        setUIClient(chromeClient);
    }

    public EnterWebChromeClient getWebChromeClient() {
        return webChromeClient;
    }

    public void loadAdapter(String mAdapter, String target, boolean hasAutoLogin) {
        String jsStr = "javascript:yspApp.notice('loadModel',{modelURL:'xcloud2json/" + mAdapter.replace("adapter://", "") + "',targetURL:'" + target + "',hasAutoLogin:" + hasAutoLogin + "})";
        loadUrl(jsStr);
    }

    public void loadJsBack(ValueCallback<String> valueCallback) {
        evaluateJavascript("yspApp.notice('back')", valueCallback);
    }

    public void loadJsNetConnected(boolean isWifi) {
        loadUrl("javascript:yspApp.notice('netConnected',{netType:'" + (isWifi ? "TYPE_WIFI" : "TYPE_MOBILE") + "'})");
    }

    public void loadJsNetDisConnected() {
        loadUrl("javascript:yspApp.notice('netDisconnected')");
    }

    public void loadJsTimeOut() {
        loadUrl("javascript:yspApp.notice('timedOut')");
    }

    public void loadJsRefresh(ValueCallback<String> valueCallback) {
        evaluateJavascript("yspApp.notice('refresh');", valueCallback);
    }
}
